/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.web30.idm.ldap.tool.impl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import org.web30.idm.model.IDMException;
import org.web30.idm.model.Web30Person;
import org.web30.idm.ldap.tool.model.IdentityLoader;
import org.web30.idm.openldap.AccountServiceOpenLDAP;
import org.web30.idm.openldap.Web30InetOrgPerson;

/**
 *
 * @author Xiaz Zhenyu
 */
public class FileLoader implements IdentityLoader {

    private String fileName = null;

    private HashMap users = null;

    private AccountServiceOpenLDAP service = null;

    public FileLoader(String fileName) {
        this.fileName = fileName;
        this.users = new HashMap();
        this.service = new AccountServiceOpenLDAP(null,0,null,null);
    }

    public HashMap getIdentities() {
        return this.users;
    }

    public boolean load() {
        try {
            BufferedReader br = new BufferedReader(new FileReader(this.fileName));
            String line = br.readLine();
            while (line != null) {                
                Web30Person user = this.getIdentity(line);
                line = br.readLine();
                if(user == null){
                    continue;
                }
                this.users.put(user.getMail(), user);
            }
            br.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public boolean addEntries() throws IDMException {
        if(this.service == null)
            return false;
        if(!this.load())
            return false;
        HashMap result = this.getIdentities();
        if(result == null)
            return false;
        Collection set = result.values();
        Iterator e = set.iterator();
        while(e.hasNext()) {
            this.service.addUser((Web30Person)e.next());
        }
        return true;
    }

    private Web30Person getIdentity(String line) {
        String[] tokens = line.split("[@.]");
        if(tokens.length < 2)
            return null;
        Web30Person user = new Web30InetOrgPerson(
            tokens[0].trim(),    //User Name as display name
            tokens[0].trim(),    //User Name
            "eds321",     //Set default password
            line.trim(),         //Set mail
            this.getDomains(line)      //Set org
         );
        return user;
    }

    private String getDomains(String id) {
        return "nec-as";
    }
}
